<template>
  <div class="route-change-view">
    <el-card shadow="never" class="main-card">
      <template #header>
        <div class="header-container">
          <div class="title-container">
            <h2 class="page-title">航班航线查询</h2>
          </div>
          <div class="search-container">
            <el-input
              v-model="searchForm.flightNumber"
              placeholder="请输入航班号"
              clearable
              class="search-input"
              style="width: 220px; margin-right: 10px;"
            />
            <el-button
              type="primary"
              @click="handleSearch"
              class="search-btn"
            >查询</el-button>
            <el-button
              plain
              @click="resetSearch"
              class="reset-btn"
            >重置</el-button>
          </div>
        </div>
      </template>
      <div class="table-container">
        <!-- 数据表格 -->
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
          :default-sort="{ prop: 'flightNumber', order: 'ascending' }"
          class="data-table"
        >
          <el-table-column
            prop="flightNumber"
            label="航班号"
            min-width="120"
            align="center"
            sortable
          />
          <el-table-column
            prop="flightAttribute"
            label="航班属性"
            min-width="120"
            align="center"
          />
          <el-table-column
            prop="departureStation"
            label="始发站"
            min-width="120"
            align="center"
          />
          <el-table-column
            prop="destinationStation"
            label="目的地"
            min-width="120"
            align="center"
          />
          <el-table-column
            prop="stopoverStations"
            label="经停站"
            min-width="140"
            align="center"
          >
            <template #default="{ row }">
              <div v-if="row.stopoverStations && row.stopoverStations.length > 0" class="compact-stopover">
                <el-tooltip effect="dark" placement="top" :content="row.stopoverStations.join('、')">
                  <div class="stopover-tags">
                    <span v-for="(station, index) in row.stopoverStations" :key="index">
                      {{ station }}<span v-if="index < row.stopoverStations.length - 1">、</span>
                    </span>
                  </div>
                </el-tooltip>
              </div>
              <span v-else class="no-stopover">无</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="180"
            fixed="right"
            align="center"
          >
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="showDetail(row)"
                class="action-btn detail-btn"
              >
                详情
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="showNewApplyDialog(row)"
                class="action-btn apply-btn"
              >
                申请
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              class="smart-pagination"
            />
          </div>
        </div>
      </div>
    </el-card>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="航班航线详情"
      width="600px"
      class="detail-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="航班号">
          <span class="detail-value">{{ currentDetail.flightNumber }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="航班属性">
          <span class="detail-value">{{ currentDetail.flightAttribute }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="始发站">
          <span class="detail-value">{{ currentDetail.departureStation }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="目的地">
          <span class="detail-value">{{ currentDetail.destinationStation }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="经停站" :span="2">
          <div v-if="currentDetail.stopoverStations && currentDetail.stopoverStations.length > 0" class="stopover-container">
            <el-tag
              v-for="(station, index) in currentDetail.stopoverStations"
              :key="index"
              size="small"
              type="info"
              class="stopover-tag"
            >
              {{ station }}
            </el-tag>
          </div>
          <span v-else class="no-stopover">无经停站</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button
          type="primary"
          @click="detailDialogVisible = false"
          class="dialog-btn close-btn"
        >
          关闭
        </el-button>
      </template>
    </el-dialog>
    <!-- 申请对话框 -->
    <el-dialog
      v-model="applyDialogVisible"
      :title="`航线变更申请 - ${applyForm.flightNumber}`"
      width="700px"
      class="split-field-dialog"
    >
      <el-descriptions :column="2" border>
        <!-- 基本信息 -->
        <el-descriptions-item label="航班号">
          <el-input
            v-model="applyForm.flightNumber"
            placeholder="请输入航班号"
            disabled
          />
        </el-descriptions-item>
        <!-- 当前航线展示 -->
        <el-descriptions-item label="当前航线">
          <div class="current-route">
            <div v-if="currentRoute" class="route-display">
              <el-tag type="info">{{ currentRoute.departureStation }}</el-tag>
              <span class="arrow">→</span>
              <template v-if="currentRoute.stopoverStations && currentRoute.stopoverStations.length > 0">
                <el-tag
                  v-for="(station, index) in currentRoute.stopoverStations"
                  :key="index"
                  type="info"
                >
                  {{ station }}
                </el-tag>
                <span class="arrow">→</span>
              </template>
              <el-tag type="info">{{ currentRoute.destinationStation }}</el-tag>
            </div>
            <div v-else class="no-route">无当前航线数据</div>
          </div>
        </el-descriptions-item>
        <!-- 拆分编辑字段 -->
        <el-descriptions-item label="始发站" :span="2">
          <el-input
            v-model="applyForm.departureStation"
            placeholder="请输入始发站三字代码"
            class="station-input"
          />
        </el-descriptions-item>
        <el-descriptions-item label="航班属性">
          <el-input
            v-model="applyForm.flightAttribute"
            placeholder="请输入航班属性代码"
          />
        </el-descriptions-item>
        <el-descriptions-item label="目的地">
          <el-input
            v-model="applyForm.destinationStation"
            placeholder="请输入目的地三字代码"
            class="station-input"
          />
        </el-descriptions-item>
        <el-descriptions-item label="经停站" :span="2">
          <div class="stopover-container">
            <el-input
              v-model="applyForm.stopoverStationsStr"
              type="textarea"
              :rows="2"
              placeholder="请输入经停站三字代码，多个经停站用逗号分隔"
              @change="updateStopoverStations"
            />
            <div class="stopover-hint">例如: SHA,CAN,SZX</div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="申请备注" :span="2">
          <el-input
            v-model="applyForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入变更原因或其他备注信息"
          />
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="applyDialogVisible = false"
            class="dialog-btn cancel-btn"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            @click="submitChange"
            class="dialog-btn submit-btn"
          >
            提交申请
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { FlightApi } from '@/api/flight'
const currentRoute = ref(null)
// 搜索表单
const searchForm = ref({
  flightNumber: ''
})
// 表格数据
const tableData = ref([])
const loading = ref(false)
// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref({
  flightNumber: '',
  flightAttribute: '',
  departureStation: '',
  destinationStation: '',
  stopoverStations: []
})
// 申请相关数据
const applyDialogVisible = ref(false)
const applyForm = ref({
  flightNumber: '',
  departureStation: '',
  flightAttribute: '',
  destinationStation: '',
  stopoverStations: [],
  stopoverStationsStr: '',
  remark: ''
})
// 获取航班航线数据
const fetchFlightRoutes = async () => {
  try {
    loading.value = true
    const response = await FlightApi.getFlightRoutes(
      pagination.value.currentPage,
      pagination.value.pageSize
    )
    if (response && response.data) {
      tableData.value = response.data
      pagination.value.total = response.totalRecords || 0
    }
  } catch (error) {
    console.error('获取航班航线数据失败:', error)
    ElMessage.error('获取数据失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}
// 按航班号查询
const handleSearch = async () => {
  const flightNumber = searchForm.value.flightNumber.trim()
  if (!flightNumber) {
    fetchFlightRoutes()
    return
  }
  try {
    loading.value = true
    const flightData = await FlightApi.getFlightRouteDetail(flightNumber)
    if (flightData && flightData.length > 0) {
      tableData.value = flightData
      pagination.value.total = flightData.length
    } else {
      tableData.value = []
      pagination.value.total = 0
      ElMessage.warning('未找到航班号: ' + flightNumber)
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}
// 重置搜索
const resetSearch = () => {
  searchForm.value.flightNumber = ''
  pagination.value.currentPage = 1
  fetchFlightRoutes()
}
// 显示详情
const showDetail = (row) => {
  currentDetail.value = { ...row }
  detailDialogVisible.value = true
}
// 分页大小改变
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  if (searchForm.value.flightNumber.trim()) {
    handleSearch()
  } else {
    fetchFlightRoutes()
  }
}
// 当前页改变
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  if (searchForm.value.flightNumber.trim()) {
    handleSearch()
  } else {
    fetchFlightRoutes()
  }
}
// 初始化加载数据
onMounted(() => {
  fetchFlightRoutes()
})
const showNewApplyDialog = (row) => {
  currentRoute.value = {
    departureStation: row.departureStation,
    destinationStation: row.destinationStation,
    stopoverStations: row.stopoverStations || []
  }
  applyForm.value = {
    flightNumber: row.flightNumber,
    departureStation: row.departureStation,
    flightAttribute: row.flightAttribute,
    destinationStation: row.destinationStation,
    stopoverStations: [...(row.stopoverStations || [])],
    stopoverStationsStr: row.stopoverStations ? row.stopoverStations.join(',') : '',
    remark: ''
  }
  applyDialogVisible.value = true
}
// 更新经停站数组
const updateStopoverStations = () => {
  if (applyForm.value.stopoverStationsStr.trim() === '') {
    applyForm.value.stopoverStations = []
  } else {
    applyForm.value.stopoverStations = applyForm.value.stopoverStationsStr
      .split(',')
      .map(s => s.trim())
      .filter(s => s !== '')
  }
}
// 修改提交方法
const submitChange = async () => {
  try {
    // 确保经停站是最新的
    updateStopoverStations()
    // 构建航线字符串
    const routeParts = [
      `${applyForm.value.departureStation}:${applyForm.value.flightAttribute}`,
      ...applyForm.value.stopoverStations.map(station => `${station}:${applyForm.value.flightAttribute}`),
      `${applyForm.value.destinationStation}:${applyForm.value.flightAttribute}`
    ]
    const payload = {
      dfltFlid: parseInt(applyForm.value.flightNumber),
      airlArptId: routeParts.join(','),
      remark: applyForm.value.remark
    }
    await axios.post('http://localhost:8081/flightUpdate/submitAirlChange', payload, {
      params: { recipientEmail: '1019399421@qq.com' }
    })
    ElMessage.success('变更申请已提交')
    applyDialogVisible.value = false
    fetchFlightRoutes()
  } catch (error) {
    console.error('提交申请失败:', error)
    ElMessage.error('提交申请失败: ' + (error.message || '未知错误'))
  }
}
</script>

<style scoped>
.route-change-view {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.main-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.search-container {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  width: 220px;
}

.search-btn,
.reset-btn {
  white-space: nowrap;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.data-table {
  flex: 1;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  background: #fff;
  border-top: 1px solid var(--el-border-color-light);
  position: sticky;
  bottom: 0;
  z-index: 1;
}

.smart-pagination {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.action-btn {
  padding: 5px 10px;
  font-size: 12px;
}

/* 经停站样式优化 */
.compact-stopover {
  display: inline-block;
  max-width: 100%;
  padding: 0 5px;
}

.stopover-tags {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
  font-size: 13px;
  color: #606266;
}

.no-stopover {
  color: #909399;
  font-style: italic;
  font-size: 13px;
}

/* 对话框样式 */
.detail-dialog,
.split-field-dialog {
  border-radius: 8px;
}

.detail-value {
  font-weight: 500;
}

.stopover-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.stopover-tag {
  margin: 2px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-btn {
  min-width: 100px;
  margin-left: 12px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .search-container {
    gap: 8px;
  }
  .search-input {
    width: 180px;
  }
}

@media (max-width: 992px) {
  .header-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .search-container {
    width: 100%;
  }

  .search-input {
    width: calc(50% - 5px);
  }

  .search-btn,
  .reset-btn {
    flex: 1;
  }
}

@media (max-width: 768px) {
  .pagination-wrapper {
    width: 100%;
    overflow-x: auto;
  }

  .smart-pagination {
    flex-wrap: wrap;
  }

  .smart-pagination :deep(.el-pagination__total),
  .smart-pagination :deep(.el-pagination__sizes),
  .smart-pagination :deep(.el-pagination__jump) {
    margin: 5px 0;
    width: 100%;
    justify-content: flex-end;
  }

  .action-buttons {
    flex-direction: column;
    gap: 5px;
  }

  .action-btn {
    width: 100%;
    margin: 2px 0;
  }
}

@media (max-width: 576px) {
  .route-change-view {
    padding: 10px;
  }

  .search-input {
    width: 100%;
  }

  .search-btn,
  .reset-btn {
    width: 100%;
  }

  .smart-pagination :deep(.btn-prev),
  .smart-pagination :deep(.btn-next),
  .smart-pagination :deep(.more) {
    display: none;
  }
}
</style>

<style>
/* 全局样式调整（非scoped） */
.el-tag--small {
  height: 24px;
  line-height: 22px;
  padding: 0 8px;
}

.el-descriptions__body {
  background-color: #fff !important;
}

.split-field-dialog .el-descriptions__label {
  width: 120px;
  text-align: right;
  font-weight: bold;
  background-color: #f5f7fa;
}

.split-field-dialog .current-route .route-display {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.split-field-dialog .current-route .arrow {
  color: #606266;
  margin: 0 4px;
}
</style>
